﻿using Blog1._0.Data;
using Blog1._0.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Until;

namespace Blog1._0.Service
{
    /// <summary>
    /// 【留言】逻辑层
    /// </summary>
    public class FeedbackService : Repository
    {
        /// <summary>
        /// 返回第一级留言数据（父级），子级为在这条评论后评论的数据
        /// </summary>
        /// <returns></returns>
        public int GetFeedList()
        {
            return this.Base().IQueryable<Guo_Feedback>().Where(t => t.ParentId == 0).Count();
        }

        /// <summary>
        /// 加载留言列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        public string GetFlowFeedback(int page, int pagesize)
        {
            var db = this.Base();
            var feed = db.IQueryable<Guo_Feedback>();
            var qq = db.IQueryable<Guo_QQUser>();
            //顶级（父级）评论
            var query = (from a in feed
                         join b in qq on new { SendId = (Int32)a.SendId } equals new { SendId = b.Id } into b_join
                         from b in b_join.DefaultIfEmpty()
                         join c in qq on new { AcceptId = (Int32)a.AcceptId } equals new { AcceptId = c.Id } into c_join
                         from c in c_join.DefaultIfEmpty()
                         where
                           a.ParentId == 0
                         orderby
                           a.CreateOn descending
                         select new FeedbackModel()
                         {
                             Id = a.Id,
                             SendId = a.SendId,
                             AcceptId = a.AcceptId,
                             Content = a.Content,
                             ParentId = a.ParentId,
                             City = a.City,
                             Equip = a.Equip,
                             CreateOn = a.CreateOn,
                             SendNickName = b.NickName,
                             AcceptNickName = c.NickName,
                             HeadShot = b.HeadShot
                         }).Skip((page - 1) * pagesize).Take(pagesize);

            //子级评论
            var query1 = (from a in feed
                          join b in qq on new { SendId = (Int32)a.SendId } equals new { SendId = b.Id } into b_join
                          from b in b_join.DefaultIfEmpty()
                          join c in qq on new { AcceptId = (Int32)a.AcceptId } equals new { AcceptId = c.Id } into c_join
                          from c in c_join.DefaultIfEmpty()
                          where
                            a.ParentId != 0
                          orderby
                            a.CreateOn descending
                          select new FeedbackModels()
                          {
                              Id = a.Id,
                              SendId = a.SendId,
                              AcceptId = a.AcceptId,
                              Content = a.Content,
                              ParentId = a.ParentId,
                              City = a.City,
                              Equip = a.Equip,
                              CreateOn = a.CreateOn,
                              SendNickName = b.NickName,
                              AcceptNickName = c.NickName,
                              HeadShot = b.HeadShot
                          }).Skip((page - 1) * pagesize).Take(pagesize);

            string feedbackHtml = CreateFeedbackHtml(query.ToList(), query1.ToList());
            return feedbackHtml;
        }

        /// <summary>
        /// 返回评论HTML字符串
        /// </summary>
        /// <param name="parentList"></param>
        /// <param name="list"></param>
        /// <returns></returns>
        private string CreateFeedbackHtml(IEnumerable<FeedbackModel> parentList, IEnumerable<FeedbackModels> list)
        {
            string OpenFeedback = Configs.GetValue("OpenFeedback");
            string replyBtn = "<a href='javascript:;' class='btn-reply' data-targetid='{0}' data-targetname='{1}'>回复</a>";
            StringBuilder sb = new StringBuilder();
            if (parentList != null && list != null)
            {
                foreach (FeedbackModel item in parentList)
                {
                    sb.AppendFormat(@"<li class='zoomIn article'>
                    <div class='comment-parent'>
                        <a name='remark-{0}'></a>
                        <img src='{1}' />
                        <div class='info'>                            
                            <span class='username'>{2}</span>
                             {3}   
                        </div>
                        <div class='comment-content'>{4}</div>
                        <p class='info info-footer'>
                            <i class='fa fa-map-marker' aria-hidden='true'></i>
                            <span>{5}</span>
                            <i class='fa fa-safari' aria-hidden='true'></i>
                            <span>{6}</span>
                            <span class='comment-time'>{7}</span>
                            {8}
                        </p>
                    </div>
                    <hr />", item.Id, item.HeadShot, item.SendNickName, item.SendId == 10 ? "<span class='blogger'>博主</span>" : "<span class='Netfriend'>网友</span>", item.Content, item.City, item.Equip, item.CreateOn, OpenFeedback == "true" ? string.Format(replyBtn, item.SendId, item.SendNickName) : "回复已关闭");
                    foreach (FeedbackModels model in list)
                    {
                        if (item.Id == model.ParentId)
                        {
                            sb.AppendFormat(@"<div class='comment-child'>
                                <a name='reply-{0}'></a>
                                <img src='{1}' >
                                <div class='info'>
                                    <span class='username'>{2}</span>
                                    {3}
                                    <span style='padding-right:0;margin-left:-5px;'> 回复 </ span>
                                    <span class='username'>{4}</span>
                                    {5}
                                    <span>{6}</span>
                                </div>
                                <p class='info'>
                                    <i class='fa fa-map-marker' aria-hidden='true'></i>
                                    <span>{7}</span>
                                    <i class='fa fa-safari' aria-hidden='true'></i>
                                    <span>{8}</span>
                                    <span class='comment-time'>{9}</span>
                                    {10}
                                </p>
                            </div><hr />", model.Id, model.HeadShot, model.SendNickName, model.SendId == 10 ? "<span class='blogger'>博主</span>" : "<span class='Netfriend'>网友</span>", model.AcceptNickName, model.AcceptId == 10 ? "<span class='blogger'>博主</span>" : "<span class='Netfriend'>网友</span>",
                            model.Content, model.City, model.Equip, model.CreateOn, OpenFeedback == "true" ? string.Format(replyBtn, model.SendId, model.SendNickName) : "回复已关闭");
                        }
                    }
                    sb.AppendFormat(@"<div class='replycontainer layui-hide'>
                            <form class='layui-form' action=''>
                                <input type='hidden' name='remarkId' value='{0}'>
                                <input type='hidden' name='targetUserId' value='0'>
                                <div class='layui-form-item'>
                                    <textarea name='replyContent' lay-verify='replyContent' placeholder='请输入回复内容' class='layui-textarea' style='min-height:80px;'></textarea>
                                </div>
                                <div class='layui-form-item'>
                                    <button class='layui-btn layui-btn-xs' lay-submit='formReply' lay-filter='formReply'>提交</button>
                                </div>
                            </form>
                        </div>
                    </li>", item.Id);
                }
            }
            return sb.ToString();
        }

        /// <summary>
        /// 查询今日留言数量
        /// </summary>
        /// <param name="OpenId"></param>
        /// <returns></returns>
        public int GetTodayFeedbackNum(string OpenId)
        {
            var db = this.Base();
            var feed = db.IQueryable<Guo_Feedback>();
            var user = db.IQueryable<Guo_QQUser>();

            var timeNow = DateTime.Now.ToString("yyyy-MM-dd");
            DateTime time1 = Convert.ToDateTime(timeNow + " 0:00:00");  //数字前记得加空格
            DateTime time2 = Convert.ToDateTime(timeNow + " 23:59:59");

            var query = (from a in
                       (from a in feed
                        join b in user on new { SendId = a.SendId } equals new { SendId = b.Id }
                        where a.CreateOn >= time1 && a.CreateOn <= time2
                        && b.OpenId == OpenId
                        select new
                        {
                            Column1 = 1,
                            Dummy = "x"
                        })
                         group a by new { a.Dummy } into g
                         select new
                         {
                             feedbackNum = g.Count()
                         }).FirstOrDefault();

            return query != null ? query.feedbackNum : 0;
        }

        /// <summary>
        /// 提交留言
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool CreateModel(FeedbackModel model)
        {
            var db = this.Base();
            Guo_Feedback feed = new Guo_Feedback();
            feed.SendId = model.SendId;
            feed.AcceptId = model.AcceptId;
            feed.Content = model.Content;
            feed.ParentId = model.ParentId;
            feed.City = model.City;
            feed.Equip = model.Equip;
            feed.CreateOn = model.CreateOn;
            db.Insert(feed);

            return db.Commit() > 0 ? true : false;
        }
    }
}
